/**
 * 功能：添加银行卡
 * 入口：钱包首页，银行卡查看更多
 * 
 */
import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import {Alert,Header,BtnGroup,Toast,ActionSheet,FormInput} from 'components/index'
import update  from 'react-addons-update'
import {DanluJsBridge,logger,http} from 'common/index'
 import {BankCardSheet} from './subpage/index'
 import { browserHistory ,Link} from 'react-router'
// redux
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as walletInfoActionsFromOtherFile from '../../store/actions/walletinfo' 

class AddBankCard extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.showAlert = this.showAlert.bind(this)
        this.state = {
            showAlert : false, //查看支持的银行卡弹窗
            choseBank : false, //选择银行弹窗
            selectBank : '', //选中的银行
            canGetCode : true, //可以获取手机验证码
            maxRemainTime : 60,
            getCodeText : "获取验证码",
            remainTime : 0, //倒计时
            queryBtnDisabled : true,
            bankCardForm:{
                cardNo : '',
                cardHolderName : '',
                danluOrderId : '',
                umpTradeNo : '',
                phoneNo : '',
                phoneCaptcha : '' ,//验证码
                danluOrderId : '',//丹露绑卡下单号
                umpTradeNo : '' //联动绑卡交易号
            },
            isCardNumValidate: false,  //卡号验证是否通过
            isValiCodeValidate:false,  //验证码验证是否通过
            isPhoneValidate:false,    //手机号验证是否通过
            bankInfo : "",

            supportCards : [],
            //验证卡号正确性
            rules :{
                bankCard : [{
                    required : true,message:'请输入卡号'
                },{
                    min : 10, message: '请输入有效的卡号'
                },{
                    max : 29, message : '请输入有效的卡号'
                }],

                phoneNo : [{
                    min : 1, message: '请输入有效的手机号'
                },{
                    max : 11, message : '请输入有效的手机号'
                },{
                    type : 'phone',message : '请输入有效的手机号'
                }],

                validCode : [{
                    min : 4,message : '请输入有效的验证码'
                },{
                    max : 6, message : '请输入有效的验证码'
                }
                // {
                //     validator : function(value,callback){
                //         if (value == '1234') {
                //             callback();
                //         }else{
                //             callback('验证码有误')
                //         }
                //     }
                // }
                ]


            }
        }
    }
    componentWillMount () { 
        var _this = this;

        //设置导航菜单
        DanluJsBridge.callHandler('setOptionMenu', {menus: [{
            title: '支持银行',
            color: '#ff888888'
        }]})
        DanluJsBridge.callHandler("setBackBtnColor", {
          color: '#ff444444'
        });

        DanluJsBridge.callHandler('setTitleBarColor', {
            color: ['#fff9f9f9','#fff9f9f9']
        }, function() {
            alert(123)
        })
        DanluJsBridge.callHandler('setTitle', {
            title: '添加银行卡',
            color: '#ff444444',
        })
        // 添加事件监听
        DanluJsBridge.registerHandler('handlerNativeMessage',function(e){
            _this.showAlert()
            if (e.event == 'optionMenuClickEvent') {
            }
        })
        
        //设置用户姓名
        this.state.bankCardForm.cardHolderName = this.props.walletinfo.user ? this.props.walletinfo.user.name  : '默认名称'

        //设置支持的银行卡列表
        var supportCards = this.props.walletinfo.supportCards || []
        this.setState({
            supportCards : supportCards
        })
        
    }
    componentDidMount(){
        var card = document.getElementById("card")
        if(card.autoFocus != true){
            card.focus();
        }
    }
    componentWillUnmount(){
        DanluJsBridge.callHandler('setOptionMenu', {menus:[{
                title: '',
                color: '#ff444444',
            }]}, function(response) {
        })
    }
    //打开弹窗
    showAlert (){
        this.setState({
            showAlert:true
        })
    }
    // 关闭弹窗
    closeAlert (){
        this.setState({
            showAlert : false
        })
    }
    //确认绑卡
    bindCard (){
        var _this = this;
        //去掉银行卡之间的空格
        var cardNo = this.state.bankCardForm.cardNo.replace(/\s+/g, "");
        var reqData = {
            "userId":this.props.walletinfo.user.userId,
            "companyId":this.props.walletinfo.user.companyId,
            "danluOrderId":this.state.bankCardForm.danluOrderId,
            "umpTradeNo":this.state.bankCardForm.umpTradeNo,
            "phoneNo":this.state.bankCardForm.phoneNo,
            "cardHolderName":this.state.bankCardForm.cardHolderName,
            "idCard":cardNo,
            "phoneCaptcha": this.state.bankCardForm.phoneCaptcha,
            "bankId":this.state.selectBank
        }

        http.post('/dlpcweb/dlpc/pc/V1/wallet/bindConfirm',reqData).then(data => {
            _this.getBindCards();
            _this.props.walletinfoActions.walletInfoUpdate({
                choosedCard : ''
            })
            DanluJsBridge.callHandler('toast', {
                content :"绑卡受理成功", type:'success',duration :  2000
            }, function(){
                browserHistory.goBack();
            })
        })
        
    }

    //获取验证码倒计时
    getVeriyCode (){
        var that = this;
        //去掉银行卡之间的空格
        var cardNo = this.state.bankCardForm.cardNo.replace(/\s+/g, "");
        var reqData = {
            "userId":this.props.walletinfo.user.userId,
            "companyId":this.props.walletinfo.user.companyId,
            "phoneNo":this.state.bankCardForm.phoneNo,
            "cardHolderName": this.state.bankCardForm.cardHolderName,
            "cardNo":cardNo,
            "bankId":this.state.selectBank
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/bindOrder',reqData).then(function(data){
                that.setState({
                    canGetCode : false,
                    remainTime : that.state.maxRemainTime
                })
                that.state.bankCardForm.danluOrderId = data.danluOrderId
                that.state.bankCardForm.umpTradeNo = data.umpTradeNo
                var timer =  setInterval(function(){
                    if (that.state.remainTime > 1) {
                        that.setState({
                            canGetCode : false,
                            remainTime : that.state.remainTime -1 
                        })
                    }else{
                        that.setState({
                            canGetCode : true,
                            getCodeText:"重新获取验证码",
                            remainTime : that.state.maxRemainTime
                        })
                        window.clearInterval(timer);
                    }
                },1000)
        })
    }

    //卡号
    CardChange (value){
        var queryBtnDisabled = !!(value.length < 10)
        this.state.bankCardForm.cardNo = value
        this.setState({ 
            bankInfo : "" ,
            isValiCodeValidate : false,
            queryBtnDisabled : queryBtnDisabled
        })
        

    }
    //手机号
    PhoneChange (value){
        this.state.bankCardForm.phoneNo = value
        var re = /^1\d{10}$/
        if(re.test(value) && this.state.isCardNumValidate){
            this.setState({
                isPhoneValidate : true
            },function(){
                this.validateForm();
            })
        }else{
            this.setState({
                isPhoneValidate : false,
                isValiCodeValidate : false
            })
        }
        
    }
    //验证码更改
    ValidateCodeChange (value){
        this.state.bankCardForm.phoneCaptcha = value
        this.validateForm();
    }
    //验证完整表单
    validateForm (){
        if ( this.state.isCardNumValidate && this.state.isPhoneValidate && this.state.bankCardForm.phoneCaptcha && this.state.bankCardForm.phoneCaptcha.length >=4) {
            this.setState({
                isValiCodeValidate : true
            })
        }else{
           this.setState({
                isValiCodeValidate : false
            }) 
        }
    }
    chooseBankCardFn(){
        this.setState({
            choseBank : true
        })
        
    }
    // 查询所属的银行
    queryUmpHomeBank (event){
        var _this = this;
        _this.setState({
            queryBtnDisabled : true
        })
        var cardNo = this.state.bankCardForm.cardNo
        if (!cardNo || cardNo.length<10) { return }
        var cardNumber = cardNo.replace(/\s/ig,'')
        var reqData = {
            "cardNo":cardNumber
        }
        http.get('/dlpcweb/dlpc/pc/V1/wallet/queryUmpHomeBank',reqData).then(function(data){
            let bankInfo = data[0] || {}
            _this.state.supportCards.map((card) => { 
                if (card.bankId == bankInfo.bankId) {
                    bankInfo.bankIconUrl = card.bankIconUrl 
                } 
            })
            _this.setState({
                isCardNumValidate : true,
                bankInfo : bankInfo,
                queryBtnDisabled : false,
                selectBank : bankInfo.bankId
            })
            
        }).catch(function (err) {
           if (err && err.status == 2 ) {
                _this.setState({
                    bankInfo : {},
                    queryBtnDisabled : false,
                    selectBank : ''
                })
            }
        })
    }
    bankChoosedFn (bank){
        if (bank.bankId) {
            this.setState({
                choseBank : false,
                selectBank : bank.bankId,
                bankInfo : bank,
                isCardNumValidate : true
            }) 
        }else{
            this.setState({
                choseBank : false
            },function(){
                this.validateForm();
            })  
        }
        
    }
    /*
     * 查询绑定的银行卡
     * 绑卡成功后返回上级页面前重新查询
     */

    getBindCards (){
        var reqData = {
            "userId": this.props.walletinfo.user.userId,
            "companyId": this.props.walletinfo.user.companyId
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/getBindCardList',reqData).then((data) =>{
            var bindCards = data || []
            this.props.walletinfoActions.walletInfoUpdate({
                bindCards : bindCards
            })
        })
    }
    render() {
        return (
            <div className="AddBankCard">
                <Header title="添加银行卡" className="wallet-hader"></Header>
                <div className="addBankContent">
                        {/* 选择银行 */}
                        {
                            this.state.choseBank == true ? 
                                <ActionSheet close={this.bankChoosedFn.bind(this)}>
                                    {
                                        this.state.supportCards.map( (item,index) =>{
                                            return <BankCardSheet card={item} key={index} choosed={item.bankId == this.state.selectBank} handleClick={this.bankChoosedFn.bind(this)}/>
                                        } )   
                                    }
                                </ActionSheet> : ''
                        }
                        
                        {/* 弹窗  */}
                        { this.state.showAlert===true ?   
                            <Alert close={this.closeAlert.bind(this)}>
                                <div >
                                    <div className="alert-content">
                                        <div className="padding10 font18 align-center">
                                            支持的银行
                                        </div>
                                        <div className="bankList">
                                            {
                                                this.state.supportCards.map( (item,index) =>{
                                                    return <li className="col-md-6  align-left ">{item.bankName}</li>
                                                } ) 
                                            }
                                        </div>   
                                        <div className="padding10"></div> 
                                    </div>
                                </div>
                                <div className="close-btn-extend" >
                                    <i onClick={this.closeAlert.bind(this)} className="iconfont icon-close1"></i>
                                </div>
                            </Alert> : ''}
                        <div >
                            <div className="form-input padding5 InputAddOn">
                                <span className="InputAddOn-item">姓名：</span>
                                <span className="InputAddOn-field">{this.state.bankCardForm.cardHolderName}</span>
                                <div className="InputAddOn-item">
                                   <span style={{color:'lightgray',paddingRight:'5px'}}>只能绑定法人本人银行卡</span>
                                </div>
                            </div>
                            <FormInput  title="卡号：" onBlur={this.queryUmpHomeBank.bind(this)} id="card" autoFocus={true} type="bankCard" pattern="[0-9]*" value={this.state.bankCardForm.cardNo} maxLength='31' onChange={this.CardChange.bind(this)} rule ={this.state.rules.bankCard}>
                                <button style={{border:'1px solid lightgray',borderRadius:5,padding:'5px 15px'}} disabled={this.state.queryBtnDisabled}  onClick={this.queryUmpHomeBank.bind(this)}>查询</button>
                            </FormInput>
                            {
                                this.state.bankInfo ? <div className="form-input padding5 InputAddOn">
                                    <span className="InputAddOn-item">银行：</span>
                                    {
                                        this.state.selectBank ? 
                                            <span className="InputAddOn-field bank-icon">
                                                <img src={this.state.bankInfo.bankIconUrl} /> {this.state.bankInfo.bankName}
                                            </span> : <span className="InputAddOn-field bank-icon"></span>
                                    }
                                    <div className="InputAddOn-item">
                                        <button onClick={this.chooseBankCardFn.bind(this)} style={{border:'1px solid lightgray',borderRadius:5}} className="padding5" >选择银行</button>
                                    </div>
                                </div> : ''
                            }
                            
                            <FormInput  title="手机号：" type="tel" value={this.state.bankCardForm.phoneNo} disabled={ !this.state.selectBank } rule ={this.state.rules.phoneNo} maxLength='11' onChange={this.PhoneChange.bind(this)}>
                                {
                                    this.state.canGetCode == 1 ? 
                                    <button style={{border:'1px solid lightgray',borderRadius:5}} className="padding5" disabled={ !this.state.isPhoneValidate } onClick={this.getVeriyCode.bind(this)}>{this.state.getCodeText}</button> : 
                                    <button style={{border:'1px solid lightgray',borderRadius:5,color:'gray'}} className="padding5">{this.state.remainTime}秒后重新获取</button>
                                }
                            </FormInput>
                            <FormInput  title="验证码：" type="number" disabled={ !this.state.selectBank } maxLength="6" value={this.state.bankCardForm.phoneCaptcha} pattern="[0-9]*"  rule ={this.state.rules.validCode} onChange={this.ValidateCodeChange.bind(this)}></FormInput>
                            <div className="bind-btn">
                                <button className='role-bg sure-btn' disabled={!this.state.isValiCodeValidate}  onClick={this.bindCard.bind(this)}>绑 定</button>
                            </div>
                        </div>
                </div>
            </div>
        )
    }








}


// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
    return {
        walletinfo: state.walletinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        walletinfoActions: bindActionCreators(walletInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(AddBankCard)
